<template>
	<div>
        <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
            <Cell v-for="(item, index) in list" :key="index" :title="item.content">
                <template slot="label">
                    <van-button size="small" type="primary" v-show="!item.is_rec" @click="startOrStopRec(item)">录音</van-button>
                    <van-button size="small" icon="play-circle-o" type="info" @click="stopAndUploadRec(item)" v-show="item.is_rec">结束&上传</van-button>
                    <van-button size="small" type="warning" @click="playRec(item)" v-show="item.audio_file !== ''">播放</van-button>
                    <van-button size="small" type="info" @click="uploadRec(item)" v-show="item.audio_file !== ''">上传</van-button>
                </template>
            </Cell>
        </van-pull-refresh>
	</div>
</template>

<script>
	import { API } from "@/libs/api";
	import { storage } from "@/libs/utils";
        import { Search, List, CellGroup, Cell, Field, Button, Toast, Dialog, PullRefresh } from "vant";
	Vue.use(CellGroup).use(Cell).use(Field).use(Button).use(PullRefresh);

	window.tab2Vue = {
		name: "tab2",
		components: { Search, List, Cell, Toast, Dialog },
		data() {
			return {
				list: [],
                isLoading: false,
				loading: false,
				finished: false,
				username: '',
				login_form: {
					username: 'wb-cjc242911',
					password: 'r79%63Eu',
				},
				recMp3: null,
				audioStreamer: null,
				is_rec: false,
			};
		},
		methods: {
            toast(msg) {
                Toast({
                    message: msg,
                    position: 'bottom',
                    closeOnClick: true,
                    duration: 1000
                });
            },
            onRefresh() {
                this.loadMore();
                this.updateCount();
            },
            updateCount() {
                this.$ac.sendEvent({
                    name: 'updateScriptCount',
                });
            },
			loadMore() {
				const that = this;
				API.scripts(this.username)
						.then((ret) => {
							const temp_list = [];
							for (let i = 0; i < ret.length; i++) {
								temp_list.push({
									'_id': ret[i]['_id'],
									'content': ret[i]['content'],
									'audio_file': '',
									'is_rec': false
								})
							}
							that.list = temp_list;

                            that.loading = false;
                            that.finished = true;
                            that.isLoading = false;
						})
						.catch((err) => {
							Dialog({
								title: '获取项目列表失败',
								message: JSON.stringify(err)
							});
                            that.loading = false;
                            that.finished = true;
                            that.isLoading = false;
						});
			},
			startOrStopRec(item) {
				const that = this;
				if (item.is_rec) {
					this.recMp3.stop(function(ret, err){
						if(ret){
							that.is_rec = false;
							item.audio_file = ret.path;
						}else{
							console.error(err.message)
						}
					});
				} else {
					// 检查是否有正在录音的
					if (that.is_rec) {
					    that.toast('正在录音中请先结束');
						return false;
					}
                    item.audio_file = "";
					item.is_rec = true;
					this.recMp3.start(function(ret,err){
						if(ret){
							if(ret.db !== undefined && ret.db > 0){
								// 一秒钟采样10次
								// console.log(ret.db);
								// that.currentDb = ret.db;
							}
						}else{
							item.is_rec = false;
							console.error(err)
						}
					});
				}

			},
			playRec(item) {
				if (this.audio_file === '') {
					this.toast('请先录音');
					return false;
				}
				this.audioStreamer.openPlayer({
					path: item.audio_file,
				}, function(ret) {
					if (!ret.status) {
						Dialog({
							title: '播放录音失败',
							message: JSON.stringify(ret)
						})
					}
				});
			},
			stopAndUploadRec(item) {
				if (!item.is_rec) {
                    this.toast('请先录音');
				}
				const that = this;
				this.recMp3.stop(function(ret, err){
					if(ret){
						item.is_rec = false;
						item.audio_file = ret.path;
						that.uploadRec(item);
					}else{
						Dialog({
							title: '结束录音失败',
							message: JSON.stringify(err)
						})
					}
				});
			},
			uploadRec(item) {
				API.uploadScript(this.username, item._id, item.audio_file)
						.then((ret) => {
							if (ret.status === 200) {
							    this.toast('上传录音');
                                this.updateCount();
							} else {
                                this.toast(ret.msg);
							}
						})
						.catch((err) => {
							Dialog({
								title: '上传失败',
								message: JSON.stringify(err)
							})
						})
			}
		},
		mounted() {
			this.username = storage.get('username');
			this.loadMore();
            this.updateCount();
		},
		created() {
			this.recMp3 = api.require('recMp3');
			this.audioStreamer = api.require('audioStreamer');
		}
	};

	export default window.tab2Vue;
</script>

<style scoped>
</style>
